namespace Gitee
{
    export class Repos
    {
        name: string = "";
        id: number = 0;
        html_url: string = "";
        fullname: string = "";
        path: string = "";
    }
    export class ReposItem
    {
        path: string = "";
        download_url: string = "";
        type: string = "";
        sha: string = "";
    }
    export class RemoteTool
    {
        access_token: string = "";
        userpath: string = "";
        //因为gitee的api 不给跨域访问，请出一个代理来
        proxyurl: string = "https://bird.ioliu.cn/v2/?url="; //快，不支持delete
        //proxyurl: string = "https://netnr-proxy.cloudno.de/"; //慢，但是支持delete
        //發現API是不需要代理的，有跨域，只是oauth這關需要跨域處理一下
        async Login_WithProxy(_username: string, _password: string): Promise<boolean>
        {
            let postoption =
            {
                grant_type: "password",
                username: _username,
                password: _password,
                client_id: "05ce1cd04ef08dde351cd868a26b6f5ce2b7b9471f18c299e4b511d74e59fc54",
                client_secret: "be35b3681b90bac2795b39318d3ddb6c874fb87ec847c89e325fd4d776a30af5",
                scope: "projects user_info issues notes",
            };
            let req: RequestInit = {
                method: "Post",
                headers: { 'Content-Type': "application/json;charset=utf-8" },
                body: JSON.stringify(postoption),
                //mode: "no-cors",
            };
            try
            {

                var response = await fetch(this.proxyurl + "https://gitee.com/oauth/token", req);

                if (response.ok)
                {
                    var data = await response.json();
                    if (data["error"] != undefined)
                    {
                        console.error("logic error:" + data["error"]);
                        return false;
                    }
                    this.access_token = data["access_token"];
                    await this.GetUserName();
                    return true;
                }
                else
                {
                    console.error("post to gitee error." + response.statusText);
                    return false;
                }
            }
            catch (e)
            {
                console.error(e);
                return false;
            }
        }
        async APIGet(api: string, params?: { [id: string]: any }): Promise<any>
        {
            if (params == undefined)
            {
                params = {};
            }
            params["access_token"] = this.access_token;
            let url = /*this.proxyurl +*/ "https://gitee.com/api" + api + "?" + RemoteTool.getParamStr(params);
            let req: RequestInit = {
                method: "Get",
                headers: { 'Content-Type': "charset=utf-8" },
            };
            try
            {

                var response = await fetch(url);

                if (response.ok)
                {
                    var data = await response.json();
                    if (data["error"] != undefined)
                    {
                        console.error("logic error:" + data["error"]);
                        return null;
                    }

                    return data;
                }
                else
                {
                    console.error("post to gitee error." + response.statusText);
                    return null;
                }
            }
            catch (e)
            {
                console.error(e);
                return null;
            }
        }
        async APIDelete(api: string, params?: { [id: string]: any }): Promise<any>
        {
            if (params == undefined)
            {
                params = {};
            }
            params["access_token"] = this.access_token;
            let url = /*this.proxyurl + */"https://gitee.com/api" + api + "?" + RemoteTool.getParamStr(params);
            let req: RequestInit = {
                method: "Delete",
                headers: { 'Content-Type': "charset=utf-8" },
            };
            try
            {

                var response = await fetch(url, req);

                if (response.ok)
                {
                    var data = await response.json();
                    if (data["error"] != undefined)
                    {
                        console.error("logic error:" + data["error"]);
                        return null;
                    }

                    return data;
                }
                else
                {
                    console.error("post to gitee error." + response.statusText);
                    return null;
                }
            }
            catch (e)
            {
                console.error(e);
                return null;
            }
        }
        async GetUserName(): Promise<string>
        {
            let json = await this.APIGet("/v5/user");
            if (json == null)
                return "";
            else
            {
                this.userpath = json["login"];
                return json["login"];

            }
        }
        async GetOwnerRepositories(): Promise<Repos[] | null>
        {
            var params = {
                type: "owner",
                sort: "full_name",
                direction: "asc",
                page: 1,
                per_page: 100,
            }
            let json = await this.APIGet("/v5/user/repos", params);
            if (json == null)
                return null;
            else
                return json;
        }
        async GetRepositoriesFiles(repos: string, path?: string): Promise<ReposItem[] | null>
        {
            var url = "/v5/repos/" + this.userpath + "/" + repos + "/contents/";

            if (path != undefined)
                url += path;
            let json = await this.APIGet(url);
            if (json == null)
                return null;
            else
                return json;
        }
        async DeleteFile(repos: string, item: ReposItem): Promise<boolean>
        {
            var params = { message: "auto delele by api.", sha: item.sha };
            var url = "/v5/repos/" + this.userpath + "/" + repos + "/contents/" + item.path;
            //delete
            let json = await this.APIDelete(url, params);
            if (json != null)
                return true;
            return false;
        }
        //
        async CreateOrUpdateFile(repos: string, itempath:string,bytes:Uint8Array):Promise<boolean>
        {
            return false;
        }

        static getParamStr(obj: { [id: string]: any }): string
        {
            let arr: string[] = [];
            for (let k in obj)
            {
                arr.push(k + "=" + obj[k]);
            }
            return arr.join("&");
        }
    }
}